import {BehaviorSubject, ReplaySubject, AsyncSubject} from "rxjs";
/**
 * Created by ztt on 2018/12/9.
 * todo:BehaviorSubject：它有一个当前值的概念。它保存了发送给消费者的最新值，当有新的消费者订阅时，会从当前值开始发送
 */
function fun01(){
    var subject = new BehaviorSubject(0); // 0是初始值
    subject.subscribe({
        next: (v:number) => console.log('observerA: ' + v)
    });
    subject.next(1);
    subject.next(2);
    subject.subscribe({
        next: (v:number) => console.log('observerB: ' + v)
    });
    subject.next(3);
}
/** todo:ReplaySubject
 * 与BehaviorSubject类似，但他可以发送旧值给订阅者
 **/
function fun02(){
    var subject = new ReplaySubject(2); // 为新的订阅者缓冲2个值
    subject.subscribe({
        next: (v) => console.log('observerA: ' + v)
    });
    subject.next(1);
    subject.next(2);
    subject.next(3);
    subject.next(4);
    console.log('- - - - -缓冲几个值，后面的订阅者将从倒数第几个值开时接收 - - - - - - - -')
    subject.subscribe({
        next: (v) => console.log('observerB: ' + v)
    });
    subject.next(5);
}
/** todo:缓存1秒以内的100个值
 * **/
function fun03(){
    var subject = new ReplaySubject(100, 1000 /* windowTime */);
    var obs=subject.subscribe({
        next: (v) => console.log('observerA: ' + v)
    });
    var i = 1;
    var t=setInterval(() => subject.next(i++), 300);
    setTimeout(() => {
        subject.subscribe({
            next: (v) => console.log('observer--->B: ' + v)
        });
        obs.unsubscribe();
    }, 3000);
    setTimeout(()=>{
        clearInterval(t);
    },4000);
}
/**
 * todo:AsyncSubject
 * 只有执行结束，才会将值发给订阅者，并且只发送最后一个值；
 */
function fun04(){
    var subject = new AsyncSubject();
    subject.subscribe({
        next: (v) => console.log('observerA: ' + v)
    });
    subject.next(1);
    subject.next(2);
    subject.next(3);
    subject.next(4);
    subject.subscribe({
        next: (v) => console.log('observerB: ' + v)
    });
    subject.next(5);
    setTimeout(()=>{
        console.log('* * * * * * * * * * * *');
        subject.complete();
    },2000)
}
fun04();